// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')

cloud.init()

const db = cloud.database()
const MAX_LIMIT = 100

// 云函数入口函数
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	const app = new TcbRouter({
		event
	})

	// 获取博客列表
	app.router('list', async (ctx, next) => {
		const keyword = event.keyword
		console.log(keyword)
		let key = {}
		if (keyword.trim() != '') {
			key = {
				content: db.RegExp({
					regexp: keyword,
					options: 'i'
				})
			}
		}
		ctx.body = await db.collection('blog').where(key).skip(event.start).limit(event.count)
		.orderBy('createTime', 'desc').get().then(res => {
			// console.log(res)
			return res
		})
	})

  // 博客详情
  app.router('detail', async (ctx, next) => {
    let blogId = event.blogId
    // 详情查询
    let detail = await db.collection('blog').where({
      _id: blogId
    }).get().then(res => {
      return res.data
    })
    // 评论查询
    const countResult = await db.collection('blog-comment').count()
    const total = countResult.total
    let commentList = {
      data: []
    }
    if (total > 0) {
      const batchTimes = Math.ceil(total / MAX_LIMIT)
      const tasks = []
      for (let i = 0; i <batchTimes; i++) {
        let promise = db.collection('blog-comment').skip(i * MAX_LIMIT).limit(MAX_LIMIT).where({
          blogId
        }).orderBy('createTime', 'desc').get()

        tasks.push(promise)
      }
      if (tasks.length > 0) {
        commentList = (await Promise.all(tasks)).reduce((acc, cur) => {
          return {
            data: acc.data.concat(cur.data)
          }
        })
      }
    }

    ctx.body = {
      commentList,
      detail
    }
  })

	// 我的发现
	app.router('getMyBlog', async (ctx, next) => {
		ctx.body = await db.collection('blog').where({
			_openid: wxContext.OPENID
		}).skip(event.start).limit(event.count).orderBy('createTime', 'desc')
		.get().then(res => {
			return res.data
		})
	})
	return app.serve()
}